//
//  YZMSuggestionSubmitViewController.m
//  YZMicroStock
//
//  Created by wangminhong on 16/4/11.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMSuggestionSubmitViewController.h"
#import "YZMSuggestionService.h"
#import "YZClient.h"
#import "YZMPopupSheet.h"
#import "YZMPickerView.h"
#import "YZMAppHelper.h"
#import <BlocksKit/UIControl+BlocksKit.h>

static NSString *const sYZMSuggestionRecommendString = @"请写下你宝贵的意见，我们客服将及时解答您的题！";

@interface YZMSuggestionSubmitViewController ()<UITextViewDelegate>

@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UIView *containerView;
@property (nonatomic, strong) UIButton *typeButton;
@property (nonatomic, strong) UITextView *contentView;
@property (nonatomic, strong) UIButton *sureButton;
@property (nonatomic, strong) YZMPopupSheet *popupSheet;
@property (nonatomic, assign) BOOL typeSelectFlag;

@end

@implementation YZMSuggestionSubmitViewController

- (void)viewDidLoad{
    
    [super viewDidLoad];
    self.view.backgroundColor = [YZMAppStyle appBackgroundColor];
    self.title = @"在线留言";
    self.navigationItem.rightBarButtonItem = [YZMAppStyle rightBarItemWithImage:@"icon_white_tel" target:self action:@selector(rightBarButtonItem)];
    
    [self createObjects];
    [self registerForKeyboardAutoWithBottomView:_bottomView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)rightBarButtonItem{
    
    [YZMAppHelper callServicePhone];
}

#pragma mark -- network

- (void)submitSuggestion{
    
    [YZClient submitSuggestionWithContent:_contentView.text andType:_typeButton.titleLabel.text success:^(NSURLResponse *response, id responseObject) {
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            
            [YZMHCMInstance popViewController:nil animated:YES];
            [[NSNotificationCenter defaultCenter] postNotificationName:sYZMSuggestionListDidUpdateNotification object:nil];
        }
        else
        {
            [topModel showMessage];
        }
    } failure:^(NSError *error) {
        [error yz_showMessage];
    }];
}

#pragma mark -- ui

- (void)createObjects{
    _bottomView = [UIView new];
    [self.view addSubview:_bottomView];
    [_bottomView mas_makeConstraints:^(MASConstraintMaker *maker){
        
        maker.left.right.bottom.equalTo(self.view);
        maker.height.mas_equalTo(0);
    }];
    
    UIScrollView *sv = [UIScrollView new];
    [self.view addSubview:sv];
    [sv mas_makeConstraints:^(MASConstraintMaker *maker){
        
        maker.left.right.top.equalTo(self.view);
        maker.bottom.equalTo(_bottomView.mas_top);
    }];
    
    _containerView = [UIView new];
    [sv addSubview:_containerView];
    [_containerView mas_makeConstraints:^(MASConstraintMaker *maker){
        
        maker.edges.equalTo(sv);
        maker.width.equalTo(sv);
    }];
    
    _typeButton = [UIButton new];
    _typeButton.backgroundColor = [UIColor whiteColor];
    _typeButton.layer.cornerRadius = 5.0;
    _typeButton.layer.masksToBounds = YES;
    _typeButton.layer.borderColor = [YZMAppStyle colorForLine].CGColor;
    _typeButton.layer.borderWidth = 1;
    [_typeButton setTitle:@"请选择留言类型" forState:UIControlStateNormal];
    [_typeButton.titleLabel setFont:[YZMAppStyle mediumSizeFont]];
    [_typeButton setTitleColor:[YZMAppStyle colorForGrayText] forState:UIControlStateNormal];
    _typeButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    _typeButton.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    [_typeButton bk_addEventHandler:^(id sender) {
        [self resignFirstResponderAll];
        [self showTypePage];
    } forControlEvents:UIControlEventTouchUpInside];
    [_containerView addSubview:_typeButton];
    [_typeButton mas_makeConstraints:^(MASConstraintMaker *maker){
        
        maker.top.left.equalTo(_containerView).offset(15);
        maker.right.equalTo(_containerView).offset(-15);
        maker.height.mas_equalTo(44);
    }];
    
    UIImageView *triangle = [UIImageView new];
    triangle.image = [UIImage imageNamed:@"icon_triangle_down_gray"];
    [_typeButton addSubview:triangle];
    [triangle mas_makeConstraints:^(MASConstraintMaker *maker){
        
        maker.right.equalTo(_typeButton).offset(-10);
        maker.centerY.equalTo(_typeButton);
        maker.width.mas_equalTo(13);
        maker.height.mas_equalTo(6);
    }];
    
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor whiteColor];
    view.layer.borderColor = [YZMAppStyle colorForLine].CGColor;
    view.layer.borderWidth = 1.0;
    view.layer.cornerRadius = 5.0;
    view.layer.masksToBounds = YES;
    [_containerView addSubview:view];
    [view mas_makeConstraints:^(MASConstraintMaker *maker){
        
        maker.left.right.equalTo(_typeButton);
        maker.top.equalTo(_typeButton.mas_bottom).offset(15);
        maker.height.mas_equalTo(120);
    }];
    
    _contentView = [UITextView new];
    _contentView.backgroundColor = [UIColor whiteColor];
    _contentView.textColor = [YZMAppStyle colorForGrayText];
    _contentView.text = sYZMSuggestionRecommendString;
    _contentView.tag = 0;
    _contentView.font = [YZMAppStyle mediumSizeFont];
    _contentView.delegate = self;
    [_contentView setKeyboardType:UIKeyboardTypeDefault];
    [view addSubview:_contentView];
    [_contentView mas_makeConstraints:^(MASConstraintMaker *maker){
        
        maker.edges.equalTo(view).insets(UIEdgeInsetsMake(10, 6, 10, 6));
    }];
    
    _sureButton = [YZMAppStyle submitButton];
    [_sureButton setTitle:@"提交" forState:UIControlStateNormal];
    [_sureButton bk_addEventHandler:^(id sender) {
        [_contentView resignFirstResponder];
        
        if (_contentView.tag==0 || _contentView.text.length == 0) {
            
            [MBProgressHUD showMessage:@"请输入后意见反馈"];
            return;
        }
        
        [self submitSuggestion];
    } forControlEvents:UIControlEventTouchUpInside];
    [_containerView addSubview:_sureButton];
    [_sureButton mas_makeConstraints:^(MASConstraintMaker *maker){
        
        maker.left.right.equalTo(_typeButton);
        maker.top.equalTo(view.mas_bottom).offset(30);
        maker.bottom.equalTo(_containerView).offset(-2);
    }];
}


- (void)showTypePage{
    
    if (!_popupSheet) {
        
        [self resignFirstResponderAll];
        
        YZMPickerView *pickerView = [YZMPickerView new];
        pickerView.selectedAction = ^(NSString *string){
            
            _typeSelectFlag = YES;
            [_typeButton setTitle:string forState:UIControlStateNormal];
            [self refreshButton:_sureButton forStatus:_typeSelectFlag && ( (_contentView.tag==0 ||_contentView.text.length == 0)?NO:YES)];
        };
        
        if ([YZMSuggestionService sharedService].typeList) {
            
            pickerView.dataSource = [YZMSuggestionService sharedService].typeList;
            
        }else{
            
            MBProgressHUD *hud = [MBProgressHUD showMessageManual:@"数据获取中"];
            
            [[YZMSuggestionService sharedService] fetchSuggestionTypeListSuccess:^{
                
                [hud hide:NO];
                pickerView.dataSource = [YZMSuggestionService sharedService].typeList;
                
            }failure:^(NSError *error){
                
                [hud hide:NO];
                [error yz_showMessage];
                return;
            }];
        }
        _popupSheet = [[YZMPopupSheet alloc] initWithTitle:@"请选择类型"];
        [_popupSheet setContent:pickerView];
    }
    
    [_popupSheet showInView:self.navigationController.view];
}

- (void)textViewDidBeginEditing:(UITextView *)textView{
    
    if (textView.tag == 0) {
        textView.text = @"";
    }
}

- (void)textViewDidEndEditing:(UITextView *)textView{
    
    if ([textView.text isEqualToString:sYZMSuggestionRecommendString]) {
        
        return;
    }
    
    if (textView.text.length == 0) {
        
        textView.tag = 0;
        textView.text = sYZMSuggestionRecommendString;
    }
}

- (void)textViewDidChange:(UITextView *)textView{
    
    if ([textView.text isEqualToString:sYZMSuggestionRecommendString]) {
        
        return;
    }
    
    if (textView.text.length == 0) {
        
        textView.tag = 0;
        textView.text = sYZMSuggestionRecommendString;
        [self refreshButton:_sureButton forStatus:NO];
        [self resignFirstResponderAll];
        
    }else{
        
        textView.tag = 1;
        [self refreshButton:_sureButton forStatus:_typeSelectFlag && (textView.text.length?YES:NO)];
    }
}


- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    
    if ([[self class] isContainsEmoji:text]) {
        
        return NO;
    }
    
    return YES;
}

- (void)refreshButton:(UIButton *)button forStatus:(BOOL)status{
    
    button.enabled = status;
    
    if (status) {
        button.enabled = YES;
        
    }else{
        button.enabled = NO;
    }
}



/*是否包含表情*/
+ (BOOL)isContainsEmoji:(NSString *)string{
    
    __block BOOL isEomji = NO;
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:
     ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
         const unichar hs = [substring characterAtIndex:0];
         
         if (hs >= 0x278b && hs<= 0x2792) {
             
             isEomji = NO;
             
         }else if (0xd800 <= hs && hs <= 0xdbff) {
             if (substring.length > 1) {
                 const unichar ls = [substring characterAtIndex:1];
                 const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                 if (0x1d000 <= uc && uc <= 0x1f77f) {
                     isEomji = YES;
                 }
             }
         } else if (substring.length > 1) {
             const unichar ls = [substring characterAtIndex:1];
             if (ls == 0x20e3) {
                 isEomji = YES;
             }
         } else {
             if (0x2100 <= hs && hs <= 0x27ff && hs != 0x263b) {
                 isEomji = YES;
             } else if (0x2B05 <= hs && hs <= 0x2b07) {
                 isEomji = YES;
             } else if (0x2934 <= hs && hs <= 0x2935) {
                 isEomji = YES;
             } else if (0x3297 <= hs && hs <= 0x3299) {
                 isEomji = YES;
             } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50|| hs == 0x231a ) {
                 isEomji = YES;
             }
         }
     }];
    
    return isEomji;
}



@end
